const userServer = require("../server/user")
const jwt = require("jsonwebtoken")
const { jwtSecretKey, expiresIn } = require("../config")
class userControl {
  async login(req, res) {
    const { username, password } = req.body
    const result = await userServer.login(username, password)
    if (result[0].length) {
      res.send({
        status: 0,
        message: "登录成功",
        token:
          "Bearer " +
          jwt.sign({ username, id: result[0][0].id }, jwtSecretKey, {
            expiresIn,
          }),
      })
    } else {
      res.cc("用户名或密码有误")
    }
  }
  async reguser(req, res) {
    const { username, password } = req.body
    // 1数据合法性校验

    // 2是否用户名被占用
    const result = await userServer.iscanadd(username)
    // 3 执行注册
    if (!result[0].length) {
      const result2 = await userServer.regutor(username, password)
      if (result2[0].affectedRows) {
        res.cc("注册成功", 0)
      } else {
        res.cc("注册失败")
      }
    } else {
      res.cc("用户名以及被占用")
    }
  }
}

module.exports = new userControl()
